// package-market/pages/lottery-edit-warehouse/index.js
const app = getApp();
import { PageScrollListMixins } from '../../../behaviors/page';
import { navBack, navTo, showLoading, hideLoading, tipToast } from '../../../common/env';
import { PACKAGE_STAR_PAGE } from '../../../constants/route';
import { ACTIVITY_STATUS_VALUE } from '../../../constants/activity';
import { getWarehouseList } from '../../../api/brd';
import { arr2Obj } from '../../../common/utils';

Page({
    mixins: [PageScrollListMixins],
    data: {
        activityInfo: {},
        modifyFlag: true,
        selectInfo: {
            map: {},
        },
    },
    onShow() {
        this._handleGetList(1);
    },
    onLoad(options) {
        app.event.addListener('sendLotteryActivityInfo', this._handleSendActivity.bind(this));
    },
    onUnload() {
        app.event.removeListener('sendLotteryActivityInfo');
    },
    _handleSendActivity(activityInfo) {
        const modifyFlag = !activityInfo.processStatus || activityInfo.processStatus === ACTIVITY_STATUS_VALUE.draft;
        this.setData({
            modifyFlag,
            activityInfo,
        });
        this._handleSelected(activityInfo.warehouseIds || []);
    },
    _handleSelected(list) {
        this.setData({
            'selectInfo.map': arr2Obj(list),
        });
    },
    async _handleGetList(pageNo) {
        !this.data.loaded && showLoading('加载中...');
        const { pageData } = this.data;
        let { ts } = pageData;
        pageNo === 1 && (ts = Date.now());
        const { rows = [], total } = await getWarehouseList({ pageSize: 100, pageNo, ts });
        this.setData({
            pageData: {
                ...pageData,
                refresh: false,
                ts,
                pageNo,
                total,
                rows: pageNo == 1 ? rows : [...pageData.rows, ...rows],
            },
        });
        if (!this.data.loaded) hideLoading(); this.setData({ loaded: true });
    },
    handleSelect(e) {
        if (!this.data.modifyFlag) {
            tipToast('活动已发布，此项不能编辑');
            return;
        }
        const id = e.detail;
        const { selectInfo } = this.data;
        selectInfo.map = {};
        if (selectInfo.map[id]) {
            delete selectInfo.map[id];
        } else {
            selectInfo.map[id] = id;
        }
        this.setData({ selectInfo });
    },
    handleNavToCreate() {
        navTo(PACKAGE_STAR_PAGE['brandWarehouseEdit']);
    },
    handleSave() {
        if (!this.data.modifyFlag) {
            navBack();
            return;
        }
        const { activityInfo, selectInfo } = this.data;
        activityInfo.warehouseIds = Object.keys(selectInfo.map);
        if (!activityInfo.warehouseIds || !activityInfo.warehouseIds.length) {
            tipToast('请选择供货仓');
            return;
        }
        app.event.trigger('getLotteryActivityInfo', activityInfo);
        navBack();
    },
})
